﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Threading;
using Coding4Fun.Phone.Controls;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;
using System.Diagnostics;
using Qplus.enums;
using Qplus.Infrastructure;
using Qplus.protocol;
using Qplus.UI;

namespace Qplus
{
    public partial class MainPage : PhoneApplicationPage
    {
        List<Qplus.UI.FriendControl> fList = new List<Qplus.UI.FriendControl>();
        String version = "1000";
        String ipAddr = "testlg.gotye.com.cn";
        String deviceID = "0b65caa0-18ab-4";
        //String appID = "0b65caa0-18ab-4c6b-aeab-5a55d9f62b6c";
        String appID = "123";
        String appVer = "1.0";

        List<business> che;

        // 构造函数
        public MainPage()
        {
            InitializeComponent();
            che = new List<business>()  
            {  
                new business() { txt = "选项1"},  
                new business() { txt = "选项2"},  
                new business() { txt = "选项3"},  
                new business() { txt = "选项4"},  
                new business() { txt = "选项5"},  
                new business() { txt = "选项6"},  
                new business() { txt = "选项7"}                  
            };
            itemsControl.ItemsSource = che;

            Qplus.UI.FriendControl search = new Qplus.UI.FriendControl()
            {
                UserID = 0,
                CtrlType = friendCtrlTypeEnum.search,
            };
            fList.Insert(0, search);
            FriendControl frd1 = new FriendControl()
            {
                UserID = 1,
                CtrlType = friendCtrlTypeEnum.friend,
                UserName = "好友1",
                BtnExBackGround = new ImageBrush()
                {
                    ImageSource = new BitmapImage(new Uri("/Qplus;component/Pic/app_info_default_icon.png", UriKind.RelativeOrAbsolute)),
                    Stretch = Stretch.None,
                }
            };
            fList.Insert(1, frd1);
            FriendControl frd2 = new FriendControl()
            {
                UserID = 1,
                CtrlType = friendCtrlTypeEnum.friend,
                //UserName = "好友2",
                BtnExBackGround = new ImageBrush()
                {
                    ImageSource = new BitmapImage(new Uri("/Qplus;component/Pic/app_info_default_icon.png", UriKind.RelativeOrAbsolute)),
                    Stretch = Stretch.None,
                }
            };
            fList.Insert(2, frd2);
            FriendControl frd3 = new FriendControl()
            {
                UserID = 1,
                CtrlType = friendCtrlTypeEnum.friend,
                UserName = "好友3",
                BtnExBackGround = new ImageBrush()
                {
                    ImageSource = new BitmapImage(new Uri("/Qplus;component/Pic/app_info_default_icon.png", UriKind.RelativeOrAbsolute)),
                    Stretch = Stretch.None,
                }
            };
            fList.Insert(3, frd3);
            flist.ItemsSource = fList;
            //enterBtn.AddHandler(Button.MouseLeftButtonDownEvent, new MouseButtonEventHandler(this.Button_MouseLeftButtonDown), true);
            //enterBtn.MouseMove += Button_MouseMove;
            //enterBtn.AddHandler(Button.MouseLeftButtonUpEvent, new MouseButtonEventHandler(this.Button_MouseLeftButtonUp), true);
        }

        #region MOVE enterBtn
//MOVE
        CompositeTransform transform;
        private void enterBtn_ManipulationStarted(object sender, ManipulationStartedEventArgs e)
        {
            enterBtn.Click += enterBtn_Click;
        }
        private void enterBtn_ManipulationDelta(object sender, ManipulationDeltaEventArgs e)
        {
            ButtonEx tmpBtn = sender as ButtonEx;
            transform = tmpBtn.RenderTransform as CompositeTransform;

            #region  缩放操作
            //if (e.DeltaManipulation.Scale.X > 0 || e.DeltaManipulation.Scale.Y > 0)
            //{
            //    double maxScale = Math.Max(e.DeltaManipulation.Scale.X, e.DeltaManipulation.Scale.Y);
            //    transform.ScaleX *= maxScale;
            //    transform.ScaleY *= maxScale;
            //}
            #endregion
            //移动操作
            transform.TranslateX += e.DeltaManipulation.Translation.X;
            transform.TranslateY += e.DeltaManipulation.Translation.Y;

            //postionInfo.Text = "当前偏移量：X:" + transform.TranslateX.ToString() + " Y:" + transform.TranslateY.ToString() + " 半径:" + (ellipse.ActualWidth / 2).ToString();
            // 表示该事件已经被处理，不要再执行后面的处理函数
            e.Handled = true;

            if (System.Math.Abs(e.DeltaManipulation.Translation.X) > 0 || System.Math.Abs(e.DeltaManipulation.Translation.Y) > 0)
            {
                enterBtn.Click -= enterBtn_Click;
            }
        }
        private void enterBtn_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)
        {
            ButtonEx tmpBtn = sender as ButtonEx;
            transform = tmpBtn.RenderTransform as CompositeTransform;

            if (transform.TranslateX > 0) transform.TranslateX = 0;
            else if (transform.TranslateX < (114 - 480)) transform.TranslateX = 114 - 480;
            if (transform.TranslateY > (768 - 116)) transform.TranslateY = 768 - 116;
            else if (transform.TranslateY < 0) transform.TranslateY = 0;
            #region NOTUSE
            //else
            //{
            //    DispatcherTimer DelayedTimer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(1) };
            //    DelayedTimer.Tick += (s, e0) =>
            //    {
            //        //perform action
            //        DelayedTimer.Stop();
            //        enterBtn.Click += enterBtn_Click;
            //    };
            //    DelayedTimer.Start();
            //}
            #endregion
        }
//CLICK
        private void enterBtn_Click(object sender, RoutedEventArgs e)
        {
            //checkNet();
            waitBar.Visibility = System.Windows.Visibility.Visible;

            Boolean res = QplusT.getInstance().loginVerify(ipAddr, version, Qplus.enums.E_LOGIN_TYPE.ELT_DEVICE,
                    deviceID, "", appID, appVer);
            KeepAlive.getInstance().startKeepAlive();
            //System.Threading.ManualResetEvent
            //System.ComponentModel.BackgroundWorker bw = new System.ComponentModel.BackgroundWorker();
            //bw.DoWork += new System.ComponentModel.DoWorkEventHandler(bw_DoWork);
            //bw.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(bw_RunWorkerCompleted);
            //bw.RunWorkerAsync();
        }
        public void gotoEntryPage()
        {
            waitBar.Visibility = System.Windows.Visibility.Collapsed;
            NavigationService.Navigate(new Uri("/UI/EntryPage.xaml?previousPageName=" + this.ToString(), UriKind.Relative));
        }
        private bool networkIsAvailable;
        private Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType _currentNetworkType; //网络连接的类型
        private bool checkNet()
        {
            bool result = false;
            networkIsAvailable = Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();//当前网络是否可用
            _currentNetworkType = Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType;//获取当前网络的类型

            ///if (networkIsAvailable)
            ///{
            ///    //return "Network Available";
            ///    //Message.Text = "联网状态";
            ///    //Message.Background = new SolidColorBrush(Colors.Green);
            ///}
            ///else
            ///{
            ///    MessageBox.Show("Network unAvailable");
            ///    return "";// "Network unAvailable";
            ///    //Message.Text = "断网状态";
            ///    //Message.Background = new SolidColorBrush(Colors.Red);
            ///}

            switch (_currentNetworkType)
            {
                case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MobileBroadbandCdma:
                    {
                        //Cdma网络
                        break;
                    }
                case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.MobileBroadbandGsm:
                    {
                        //Csm网络
                        break;
                    }
                case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Wireless80211:
                    {
                        //Wireless网络
                        break;
                    }
                case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.Ethernet:
                    {
                        //Ethernet网络
                        break;
                    }
                case Microsoft.Phone.Net.NetworkInformation.NetworkInterfaceType.None:
                    {
                        //网络不可用
                        result = false;
                        break;
                    }
                default:
                    //其他的网络
                    break;
            }
            return result;
        }

        void bw_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
        {
            //throw new NotImplementedException();
            //_BasePage.BackKeyPress -= BasePage_BackKeyPress;
            System.Threading.Thread.Sleep(2000);//do something

            
            bool tmp = Qplus.UI.QplusT.getInstance().loginUserServer(
                UIData.getInstance().L2C.Ip,
                UIData.getInstance().L2C.Port,
                "1000",
                "",
                UIData.getInstance().L2C.Key,
                UIData.getInstance().L2C.UserID);
            Debug.WriteLine("@@");
        }
        void bw_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
        {
            //throw new NotImplementedException();
            //if (pc.IsShown)
            //{
            //    pc.Close();
            //}
            //else
            //{
            //    NavigationService.StopLoading();
            //}
        }
#if false
        private void enterBtn_Click(object sender, RoutedEventArgs e)
        {   
            if (iswaiting == false)
            {
                Boolean res = QplusT.getInstance().loginVerify(ipAddr, version, E_LOGIN_TYPE.ELT_DEVICE,
                        deviceID, "", appID, appVer);

                KeepAlive.getInstance().startKeepAlive();

                //PopupContainer pc = new PopupContainer(this);
                //WaitControl waitCtrl = new WaitControl();
                //pc.Show(waitCtrl);
                WaitControl waitCtrl = new WaitControl() { VerticalAlignment = System.Windows.VerticalAlignment.Bottom};
                LayoutRoot.Children.Add(waitCtrl);
                DispatcherTimer DelayedTimer = new DispatcherTimer() { Interval = TimeSpan.FromSeconds(5) };
                DelayedTimer.Tick += (s, e0) =>
                {
                    //perform action
                    DelayedTimer.Stop();
                    iswaiting = false;
                    LayoutRoot.Children.Remove(waitCtrl);
                    NavigationService.Navigate(new Uri("/UI/EntryPage.xaml", UriKind.Relative));
                };
                DelayedTimer.Start();
                iswaiting = true;
            }
        }
#endif
        #endregion
#region TEST
        int i = 1;
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //fList.RemoveAt(i++);
            //fList.ElementAt(2).UserID = 20;
            if (null != che)
            {
                che.ElementAt(i++).txt = "changed";
                che.RemoveAt(i++);
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            byte[] key = new byte[32];
            key[0] = 52;
            key[1] = 51;
            key[2] = 50;
            key[3] = 65;
            key[4] = 52;
            key[5] = 48;
            key[6] = 48;
            key[7] = 68;
            key[8] = 57;
            key[9] = 70;
            key[10] = 67;
            key[11] = 70;
            key[12] = 52;
            key[13] = 49;
            key[14] = 52;
            key[15] = 99;
            key[16] = 57;
            key[17] = 49;
            key[18] = 54;
            key[19] = 51;
            key[20] = 51;
            key[21] = 55;
            key[22] = 54;
            key[23] = 53;
            key[24] = 68;
            key[25] = 48;
            key[26] = 50;
            key[27] = 49;
            key[28] = 56;
            key[29] = 56;
            key[30] = 48;
            key[31] = 56;
            bool tmp = Qplus.UI.QplusT.getInstance().loginUserServer("60.29.239.47\0\0\0\0", 8889, "1000", "0b65caa0-18ab-4", key, 8615);
        }
#endregion
    }
    public class business
    {
        public string txt { get; set; }
    } 
}